package com.eiletxie.springcloud.filter;

import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.Arrays;
import java.util.List;

import static org.springframework.cloud.gateway.support.GatewayToStringStyler.filterToStringCreator;

@Component
public class MyFilterGatewayFilterFactory
        extends AbstractGatewayFilterFactory<MyFilterGatewayFilterFactory.Config> {

    public MyFilterGatewayFilterFactory() {
        super(Config.class);
    }
    private String NAME="removeHeader";
    @Override
    public GatewayFilter apply(Config config) {
        return new GatewayFilter() {
            @Override
            public Mono<Void> filter(ServerWebExchange exchange,
                                     GatewayFilterChain chain) {
                ServerHttpRequest request = exchange.getRequest();
                HttpHeaders headers = request.getHeaders();

                if(!headers.containsKey(config.getRemoveHeader())){
                    //headers.set(config.getRemoveHeader(),"jwt");
                    request.mutate().header(config.getRemoveHeader(),"jwt");
                   // headers.remove(config.getRemoveHeader());
                }

                return chain.filter(exchange);
            }
            @Override
            public String toString() {
                return filterToStringCreator(MyFilterGatewayFilterFactory.this)
                        .append("NAME", config.getRemoveHeader()).toString();
            }
        };
    }

    @Override
    public List<String> shortcutFieldOrder() {
        return Arrays.asList(NAME);
    }

    public static class Config {

        private String removeHeader;

        public String getRemoveHeader() {
            return removeHeader;
        }

        public void setRemoveHeader(String removeHeader) {
            this.removeHeader = removeHeader;
        }
    }
}
